package com.cq.hd.product.factory;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.NoUtils;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.dto.UpdateActiveCountDto;
import com.cq.hd.member.api.vo.BusinessVo;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.dto.ActiveGoodsSummaryDto;
import com.cq.hd.product.mapper.*;
import com.cq.hd.product.po.*;
import com.cq.hd.product.service.TbActiveLabelService;
import com.cq.hd.product.validator.ActivePublishValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author much
 * @since 2024/05/18 10:48
 */
@Slf4j
@Component
public class GroupEnrollActiveReleaseHandler extends AbstractActiveReleaseHandler {

    @Resource
    private TbBusinessApi businessApi;
    @Resource
    private TbGoodsMapper goodsMapper;
    @Resource
    private TbActiveGoodsStockMapper activeGoodsStockMapper;
    @Resource
    private TbActiveGoodsSubsidyMapper activeGoodsSubsidyMapper;
    @Resource
    private TbActiveAgentMapper activeAgentMapper;
    @Resource
    private TbActiveRedPacketMapper activeRedPacketMapper;
    @Resource
    private TbActiveGoodsMapper activeGoodsMapper;
    @Resource
    private TbActiveDiscountMapper activeDiscountMapper;
    @Resource
    private TbActiveStepPriceMapper activeStepPriceMapper;
    @Resource
    private TbActiveEnrollInfoMapper activeEnrollInfoMapper;
    @Resource
    private TbActiveMapper activeMapper;
    @Resource
    private TbActiveLabelService activeLabelService;
    @Resource
    private PlatformTransactionManager transactionManager;

    @Override
    protected Integer getType() {
        return ActiveTypeEnum.GROUP_ENROLL.getValue();
    }

    @Override
    public Long saveActiveData(ActiveReleaseDto activeReleaseDto) {
//        if (activeReleaseDto.getLimitBuyNum() == null) {
//            activeReleaseDto.setLimitBuyNum(99999999);
//        }
        // 报名次数限制前端改成限购数量
        activeReleaseDto.setLimitEnrollNum(activeReleaseDto.getLimitBuyNum());

        // 设置默认值
        setDefaultValue(activeReleaseDto);
        // 表单校验
        ActivePublishValidator.validate(activeReleaseDto);

        // 商品信息概览
        ActiveGoodsSummaryDto activeGoodsSummaryDto = summarizeActiveGoods(activeReleaseDto);
        // 如果是手动设置补贴，校验补贴金额是否等于商品总价-活动价格
        checkManualSubsidySetting(activeReleaseDto, activeGoodsSummaryDto);
        // 校验发布次数
        checkBusinessPublishCount(activeReleaseDto);

        return save(activeReleaseDto, activeGoodsSummaryDto);
    }

    private TbActivePo convertToActivePo(ActiveReleaseDto activeReleaseDto, ActiveGoodsSummaryDto activeGoodsSummaryDto) {
        TbActivePo tbActivePo = new TbActivePo();
        BeanUtils.copyProperties(activeReleaseDto, tbActivePo);
        tbActivePo.setContent(JSON.toJSONString(activeReleaseDto.getActiveContents()));
        tbActivePo.setActiveNo(NoUtils.getActiveNo());
        tbActivePo.setTotalStock(activeReleaseDto.getTotalStock());
        tbActivePo.setRemainStock(activeReleaseDto.getTotalStock());
        tbActivePo.setStartTime(LocalDateUtil.toLocalDateTime(activeReleaseDto.getStartTime(), Constant.YYYY_MM_DD_HH_MM_SS));
        tbActivePo.setEndTime(LocalDateUtil.toLocalDateTime(activeReleaseDto.getEndTime(), Constant.YYYY_MM_DD_HH_MM_SS));
        tbActivePo.setValidStartTime(LocalDateUtil.toLocalDateTime(activeReleaseDto.getValidStartTime(), Constant.YYYY_MM_DD_HH_MM_SS));
        tbActivePo.setValidEndTime(LocalDateUtil.toLocalDateTime(activeReleaseDto.getValidEndTime(), Constant.YYYY_MM_DD_HH_MM_SS));
        BigDecimal activeRedPacket = Optional.ofNullable(activeReleaseDto.getActiveRedPacket())
                .map(ActiveRedPacketSonDto::getFirstRedPacketAmt).orElse(BigDecimal.ZERO);
        tbActivePo.setFirstRedPacketAmt(activeRedPacket);
        tbActivePo.setCreateTime(LocalDateTime.now());
        // 如果是发布，则记录发布时间
        if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
            tbActivePo.setReleaseTime(LocalDateTime.now());
        }

        // 处理关联的商户id
        if (CollectionUtils.isEmpty(activeGoodsSummaryDto.getMerchantIds())) {
            tbActivePo.setRelationMerchantIds("0");
        } else {
            tbActivePo.setRelationMerchantIds(String.join(",", activeGoodsSummaryDto.getMerchantIds()) + ",");
        }

        return tbActivePo;
    }

    // 校验商家的活动发布次数
    private void checkBusinessPublishCount(ActiveReleaseDto activeReleaseDto) {
        if (ActiveStateEnum.NO_START.getValue().equals(activeReleaseDto.getActiveState())) {
            // 判断商家发布活动次数是否足够
            BusinessVo businessVo = businessApi.getActiveCount(activeReleaseDto.getUserId(), activeReleaseDto.getBusinessId()).unpack();
            if (businessVo != null) {
                Integer activeCount = businessVo.getActiveCount();
                if (activeCount < 1) {
                    Throw.isBusinessException("发布活动次数不足");
                }
            }
        }
    }

    // 如果是手动设置补贴，校验补贴金额是否等于商品总价-活动价格
    private void checkManualSubsidySetting(ActiveReleaseDto activeReleaseDto, ActiveGoodsSummaryDto activeGoodsSummaryDto) {
        Integer subsidyState = activeReleaseDto.getSubsidyState();
        if (SubsidyStateEnum.MANUAL.getValue().equals(subsidyState)) {
            List<ActiveGoodsSubsidySonDto> activeGoodsSubsidy = activeReleaseDto.getActiveGoodsSubsidy();
            if (CollectionUtils.isEmpty(activeGoodsSubsidy)) {
                Throw.isBusinessException("请设置活动商品的补贴金额");
            }

            // 判断商品补贴列表个数是否与活动商品总个数相同
            if (activeGoodsSubsidy.size() != activeGoodsSummaryDto.getGoodsNum()) {
                Throw.isBusinessException("活动商品补贴与活动商品个数不等");
            }

            // 累加填写的补贴金额
            BigDecimal totalSubsidyAmt = BigDecimal.ZERO;
            for (ActiveGoodsSubsidySonDto activeGoodsSubsidySonDto : activeGoodsSubsidy) {
                BigDecimal goodsPrice = activeGoodsSubsidySonDto.getGoodsPrice();
                BigDecimal getSubsidyAmt = activeGoodsSubsidySonDto.getSubsidyAmt();
                if (getSubsidyAmt != null) {
                    // 补贴金额不能大于商品价格
                    if (goodsPrice.compareTo(getSubsidyAmt) < 0) {
                        Throw.isBusinessException("补贴金额不能超过商品价格");
                    }

                    if (getSubsidyAmt.compareTo(BigDecimal.ZERO) > 0) {
                        totalSubsidyAmt = totalSubsidyAmt.add(getSubsidyAmt);
                    }
                }

                Integer mulState = activeGoodsSubsidySonDto.getMulState();
                if (MulStateEnum.YES.getValue().equals(mulState)) {
                    // 商品id/商户id(如果是多商户通用券，则会存在多个，使用英文逗号分割)
                    String goodsId = activeGoodsSubsidySonDto.getGoodsId();
                    if (!StringUtils.isEmpty(goodsId)) {
                        String[] splitGoodsIdArr = goodsId.split(",");
                        activeGoodsSummaryDto.getMerchantIds().addAll(Arrays.asList(splitGoodsIdArr));
                    }
                } else {
                    activeGoodsSummaryDto.getMerchantIds().add(String.valueOf(activeGoodsSubsidySonDto.getMerchantId()));
                }
            }

            // 单订单补贴金额=商品价格总和-活动价+单个红包金额+佣金
            BigDecimal firstRedPacketAmt = Optional.ofNullable(activeReleaseDto.getActiveRedPacket())
                    .map(ActiveRedPacketSonDto::getFirstRedPacketAmt)
                    .orElse(BigDecimal.ZERO);
            BigDecimal actualCommissionAmt = activeReleaseDto.getActivePrice()
                    .multiply(activeReleaseDto.getCommissionRate()).divide(new BigDecimal("100"), 2, RoundingMode.DOWN);

            BigDecimal needTotalSubsidyAmt = activeGoodsSummaryDto.getGoodsTotalAmt()
                    .subtract(activeReleaseDto.getActivePrice())
                    .add(firstRedPacketAmt).add(actualCommissionAmt);

            // 填写的补贴金额总和（没加佣金和单个红包的）须等于单订单补贴金额
            if (totalSubsidyAmt.compareTo(needTotalSubsidyAmt) != 0) {
                Throw.isBusinessException("补贴金额有误，请重新填写");
            }
        }
    }

    private ActiveGoodsSummaryDto summarizeActiveGoods(ActiveReleaseDto activeReleaseDto) {
        // 商户id
        Set<String> merchantIdsSet = new HashSet<>();
        // 商品总数
        int goodsNums = 0;
        // 商品总价
        BigDecimal goodsTotalAmt = BigDecimal.ZERO;
        for (ActiveGoodsSonDto activeGood : activeReleaseDto.getActiveGoods()) {
            BigDecimal goodsPrice = activeGood.getGoodsPrice();
            Integer goodsNum = activeGood.getGoodsNum();

            if (goodsNum == null || goodsNum <= 0) {
                Throw.isBusinessException("活动商品个数有误，请重新设置");
            }

            if (goodsPrice == null || goodsPrice.compareTo(BigDecimal.ZERO) <= 0) {
                activeGood.setGoodsPrice(BigDecimal.ZERO);
//                Throw.isBusinessException("活动商品价格有误，请重新设置");
            }

            BigDecimal price = goodsPrice.multiply(new BigDecimal(String.valueOf(goodsNum)));
            goodsTotalAmt = goodsTotalAmt.add(price);
            goodsNums += goodsNum;
            // 商品id/商户id(如果是多商户通用券，则会存在多个，使用英文逗号分割)
            String goodsId = activeGood.getGoodsId();

            Integer mulState = activeGood.getMulState();
            if (MulStateEnum.YES.getValue().equals(mulState)) {
                if (StringUtils.isEmpty(goodsId)) {
                    log.error("多商户通用券[{}]未设置可用商户", activeGood.getGoodsName());
                    Throw.isBusinessException("多商户通用券[" + activeGood.getGoodsName() + "]未设置可用商户");
                }

                String[] splitGoodsIdArr = goodsId.split(",");
                merchantIdsSet.addAll(Arrays.asList(splitGoodsIdArr));
            } else {
                if (StringUtils.isEmpty(goodsId)) {
                    log.error("活动商品[{}]id为空", activeGood.getGoodsName());
                    Throw.isBusinessException("活动商品[" + activeGood.getGoodsName() + "]数据错误");
                }

                // 校验活动商品是否处于上架中
                TbGoodsPo tbGoodsPo = goodsMapper.selectById(goodsId);
                // 商品状态（1-待发布(草稿箱)，2-已下架(待发售)，3-已上架）
                if (tbGoodsPo == null || tbGoodsPo.getDelState() != 0) {
                    log.error("活动商品[{}]已下架，goodsId：{}", activeGood.getGoodsName(), activeGood.getGoodsId());
                    Throw.isBusinessException("活动商品[" + activeGood.getGoodsName() + "]已下架，请重新添加商品");
                }

                if (!GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
                    log.error("活动商品[{}]已下架，goodsId：{}", activeGood.getGoodsName(), activeGood.getGoodsId());
                    Throw.isBusinessException("活动商品[" + activeGood.getGoodsName() + "]已下架，请重新添加商品");
                }
                merchantIdsSet.add(String.valueOf(activeGood.getMerchantId()));
            }
        }
        return new ActiveGoodsSummaryDto(goodsNums, merchantIdsSet, goodsTotalAmt);
    }

    private void setDefaultValue(ActiveReleaseDto activeReleaseDto) {
        if (activeReleaseDto.getZeroState() != null
                && ZeroStateEnum.YES.getValue().equals(activeReleaseDto.getZeroState())) {
            // 零元购默认活动价格为0
            activeReleaseDto.setActivePrice(BigDecimal.ZERO);
            // 零元购活动补贴必须走自动按比例分摊，不能手动设置
            activeReleaseDto.setSubsidyState(SubsidyStateEnum.AUTO.getValue());
        }
        // 团购+报名混合时，取报名人数限制作为库存
        if (activeReleaseDto.getTotalStock() == null) {
            if (StepPriceStateEnum.YES.getValue().equals(activeReleaseDto.getStepPriceState())) {
                // 根据报名人数升序
                List<ActiveStepPriceSonDto> activeStepPriceSons = activeReleaseDto.getActiveStepPrices().stream()
                        .sorted(Comparator.comparing(ActiveStepPriceSonDto::getEnrollNum))
                        .collect(Collectors.toList());
                // 获取阶梯最大人数
                activeReleaseDto.setTotalStock(activeStepPriceSons.get(activeStepPriceSons.size() - 1).getEnrollNum());
            } else {
                activeReleaseDto.setTotalStock(activeReleaseDto.getEnrollNum());
            }
        }
//        // 限购
//        if (activeReleaseDto.getLimitBuyNum() == null) {
//            activeReleaseDto.setLimitBuyNum(activeReleaseDto.getLimitEnrollNum());
//        }
    }

    private Long save(ActiveReleaseDto activeReleaseDto, ActiveGoodsSummaryDto activeGoodsSummaryDto) {
        TbActivePo tbActivePo = convertToActivePo(activeReleaseDto, activeGoodsSummaryDto);
        ActiveRedPacketSonDto activeRedPacket = activeReleaseDto.getActiveRedPacket();
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            // 添加活动数据
            int count;
            if (tbActivePo.getId() == null) {
                // 添加活动
                count = activeMapper.insert(tbActivePo);
            } else {
                // 修改活动
                count = activeMapper.updateById(tbActivePo);
                // 删除旧的活动关联数据
                deleteOldActiveRelationData(tbActivePo.getId());
            }
            if (count == 0) {
                log.error("添加活动失败，保存活动数据异常");
                Throw.isBusinessException("添加活动失败");
            }
            // 活动商品数据
            saveActiveGoodsData(activeReleaseDto, tbActivePo);
            // 活动商品补贴数据
            saveActiveGoodsSubsidyData(activeReleaseDto, tbActivePo.getId());
            // 活动折扣数据
            saveActiveDiscount(activeReleaseDto, tbActivePo.getId());
            // 经纪人数据
            saveActiveAgentData(activeReleaseDto, tbActivePo.getId());
            // 添加活动红包数据
            saveActiveRedPacketData(activeReleaseDto, activeRedPacket, tbActivePo.getId());
            // 添加活动阶梯关联数据
            saveActiveStepPriceData(activeReleaseDto, tbActivePo.getId());
            // 添加活动报名信息数据
            saveActiveEnrollData(activeReleaseDto, tbActivePo.getId());
            // 添加活动标签关联
            List<Long> labelIds = Collections.emptyList();
            if (!CollectionUtils.isEmpty(activeReleaseDto.getLabels())) {
                labelIds = activeReleaseDto.getLabels().stream().map(ActiveLabelDto::getId).collect(Collectors.toList());
            }
            activeLabelService.saveActiveLabels(tbActivePo.getId(), labelIds);

            // 营销活动 - 拼团
            if (PromotionTypeEnum.GROUP_BUY.name().equals(activeReleaseDto.getPromotionType())) {
                activeReleaseDto.setId(tbActivePo.getId());
                activeGroupBuyService.saveGroupBuyActive((GroupBuyActiveReleaseDto) activeReleaseDto);
            }

            // 如果是发布活动，则扣除商家活动次数，并记录活动次数流水
            updateBusinessActiveCount(activeReleaseDto, tbActivePo, LocalDateTime.now(), tbActivePo.getId());

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<添加团购活动>事务异常回滚", e);
            Throw.isBusinessException(e.getMessage());
        }

        return tbActivePo.getId();
    }

    private void deleteOldActiveRelationData(Long activeId) {
        // 删除活动商品关联表
        activeGoodsMapper.delete(new QueryWrapper<TbActiveGoodsPo>().eq("active_id", activeId));
        // 删除活动商品补贴数据
        activeGoodsSubsidyMapper.delete(new QueryWrapper<TbActiveGoodsSubsidyPo>().eq("active_id", activeId));
        // 删除活动折扣关联数据
        activeDiscountMapper.delete(new QueryWrapper<TbActiveDiscountPo>().eq("active_id", activeId));
        // 删除活动经纪人关联数据
        activeAgentMapper.delete(new QueryWrapper<TbActiveAgentPo>().eq("active_id", activeId));
        // 删除活动红包数据
        activeRedPacketMapper.delete(new QueryWrapper<TbActiveRedPacketPo>().eq("active_id", activeId));
        // 删除活动阶梯数据
        activeStepPriceMapper.delete(new QueryWrapper<TbActiveStepPricePo>().eq("active_id", activeId));
        // 删除活动报名信息数据
        activeEnrollInfoMapper.delete(new QueryWrapper<TbActiveEnrollInfoPo>().eq("active_id", activeId));
    }

    // 添加活动报名信息数据
    private void saveActiveEnrollData(ActiveReleaseDto activeReleaseDto, Long activeId) {
        List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeReleaseDto.getActiveEnrollInfos();
        if (!CollectionUtils.isEmpty(activeEnrollInfos)) {
            for (ActiveEnrollInfoSonDto activeEnrollInfo : activeEnrollInfos) {
                TbActiveEnrollInfoPo tbActiveEnrollInfoPo = new TbActiveEnrollInfoPo();
                tbActiveEnrollInfoPo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveEnrollInfoPo.setActiveId(activeId);
                tbActiveEnrollInfoPo.setType(activeEnrollInfo.getType());
                tbActiveEnrollInfoPo.setTitle(activeEnrollInfo.getTitle());
                if (ActiveEnrollInfoTypeEnum.SINGLE.getValue().equals(activeEnrollInfo.getType())
                        || ActiveEnrollInfoTypeEnum.MULTIPLE.getValue().equals(activeEnrollInfo.getType())) {
                    tbActiveEnrollInfoPo.setContent(JSON.toJSONString(activeEnrollInfo.getActiveEnrollInfoOptions()));
                }
                tbActiveEnrollInfoPo.setMustState(activeEnrollInfo.getMustState());
                tbActiveEnrollInfoPo.setSort(activeEnrollInfo.getSort());
                tbActiveEnrollInfoPo.setCreateTime(LocalDateTime.now());
                int count = activeEnrollInfoMapper.insert(tbActiveEnrollInfoPo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动报名信息数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }
        }
    }

    // 添加活动阶梯关联数据
    private void saveActiveStepPriceData(ActiveReleaseDto activeReleaseDto, Long activeId) {
        if (StepPriceStateEnum.YES.getValue().equals(activeReleaseDto.getStepPriceState())) {
            for (ActiveStepPriceSonDto activeStepPrice : activeReleaseDto.getActiveStepPrices()) {
                TbActiveStepPricePo tbActiveStepPricePo = new TbActiveStepPricePo();
                tbActiveStepPricePo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveStepPricePo.setActiveId(activeId);
                tbActiveStepPricePo.setEnrollNum(activeStepPrice.getEnrollNum());
                tbActiveStepPricePo.setEnrollPrice(activeStepPrice.getEnrollPrice());
                tbActiveStepPricePo.setCreateTime(LocalDateTime.now());
                int count = activeStepPriceMapper.insert(tbActiveStepPricePo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动阶梯关联数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }
        }
    }

    // 如果是发布活动，则扣除商家活动次数，并记录活动次数流水
    private void updateBusinessActiveCount(ActiveReleaseDto activeReleaseDto, TbActivePo tbActivePo, LocalDateTime nowLocalDateTime, Long activeId) {
        if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
            UpdateActiveCountDto updateActiveCountDto = new UpdateActiveCountDto();
            updateActiveCountDto.setBusinessId(activeReleaseDto.getBusinessId());
            updateActiveCountDto.setUserId(activeReleaseDto.getUserId());
            updateActiveCountDto.setRelationId(activeId);
            updateActiveCountDto.setTradeActiveCount(1);
            updateActiveCountDto.setTradeType(ActiveCountTradeTypeEnum.RELEASE_ACTIVE.getValue());
            updateActiveCountDto.setTradeTime(nowLocalDateTime);
            Boolean updateState = businessApi.subActiveCount(updateActiveCountDto).unpack();
            if (!updateState) {
                log.error("添加活动失败，扣除发布活动个数异常");
                Throw.isBusinessException("发布活动次数不足");
            }
        }
    }

    private void saveActiveRedPacketData(ActiveReleaseDto activeReleaseDto, ActiveRedPacketSonDto activeRedPacket, Long activeId) {
        if (activeRedPacket != null) {
            TbActiveRedPacketPo tbActiveRedPacketPo = new TbActiveRedPacketPo();
            tbActiveRedPacketPo.setBusinessId(activeReleaseDto.getBusinessId());
            tbActiveRedPacketPo.setActiveId(activeId);
            tbActiveRedPacketPo.setTitle("新人首单优惠");
            tbActiveRedPacketPo.setAmt(activeRedPacket.getFirstRedPacketAmt());
            tbActiveRedPacketPo.setActiveTitle(activeReleaseDto.getActiveTitle());
            tbActiveRedPacketPo.setTotalNum(activeRedPacket.getRedPacketNum());
            tbActiveRedPacketPo.setRemainNum(activeRedPacket.getRedPacketNum());
            tbActiveRedPacketPo.setValidDay(activeRedPacket.getValidDay());
            tbActiveRedPacketPo.setCreateTime(LocalDateTime.now());

            int count = activeRedPacketMapper.insert(tbActiveRedPacketPo);
            if (count == 0) {
                log.error("添加活动失败，保存活动红包数据异常");
                Throw.isBusinessException("添加活动失败");
            }
        }
    }

    // 添加活动经纪人关联数据
    private void saveActiveAgentData(ActiveReleaseDto activeReleaseDto, Long activeId) {
        int count;
        if (AgentNumStateEnum.NO.getValue().equals(activeReleaseDto.getAgentNumState()) && !CollectionUtils.isEmpty(activeReleaseDto.getAgentIds())) {
            for (Long agentId : activeReleaseDto.getAgentIds()) {
                TbActiveAgentPo tbActiveAgentPo = new TbActiveAgentPo();
                tbActiveAgentPo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveAgentPo.setActiveId(activeId);
                tbActiveAgentPo.setAgentId(agentId);
                tbActiveAgentPo.setCreateTime(LocalDateTime.now());

                count = activeAgentMapper.insert(tbActiveAgentPo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动经纪人关联数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }
        }
    }


    private void saveActiveGoodsData(ActiveReleaseDto activeReleaseDto, TbActivePo tbActivePo) {
        // 校验活动商品库存是否充足
        // 添加活动商品关联数据，添加商品活动库存表，扣减商品库存，增加冻结库存数据
        Long activeId = tbActivePo.getId();
        for (ActiveGoodsSonDto activeGood : activeReleaseDto.getActiveGoods()) {
            Integer goodsNum = activeGood.getGoodsNum();
            Integer mulState = activeGood.getMulState();
            if (mulState == null) {
                Throw.isBusinessException("活动商品数据异常");
            }

            if (MulStateEnum.NO.getValue().equals(mulState)) {
                // 如果是发布活动，则扣除商品库存
                if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
                    int subTotalStock = goodsNum * tbActivePo.getTotalStock();

                    // 扣除商品的库存
                    int count = goodsMapper.subStock(Long.parseLong(activeGood.getGoodsId()), subTotalStock);
                    if (count == 0) {
                        log.error("添加活动失败，扣减商品库存异常");
                        Throw.isBusinessException("商品【" + activeGood.getGoodsName() + "】库存不足");
                    }

                    TbActiveGoodsStockPo tbActiveGoodsStockPo = new TbActiveGoodsStockPo();
                    tbActiveGoodsStockPo.setBusinessId(activeReleaseDto.getBusinessId());
                    tbActiveGoodsStockPo.setMerchantId(activeGood.getMerchantId());
                    tbActiveGoodsStockPo.setActiveId(activeId);
                    tbActiveGoodsStockPo.setGoodsId(Long.parseLong(activeGood.getGoodsId()));
                    tbActiveGoodsStockPo.setFreezeStock(subTotalStock);
                    tbActiveGoodsStockPo.setCreateTime(LocalDateTime.now());
                    count = activeGoodsStockMapper.insert(tbActiveGoodsStockPo);
                    if (count == 0) {
                        log.error("添加活动失败，保存商品活动库存数据异常");
                        Throw.isBusinessException("添加活动失败");
                    }
                }
            } else {
                // 将多商户通用券的默认图片设置
                activeGood.setGoodsImgs(Constant.MUL_MERCHANT_GOODS_IMG_URL);
            }

            TbActiveGoodsPo tbActiveGoodsPo = new TbActiveGoodsPo();
            BeanUtils.copyProperties(activeGood, tbActiveGoodsPo);
            tbActiveGoodsPo.setBusinessId(activeReleaseDto.getBusinessId());
            tbActiveGoodsPo.setActiveId(activeId);
            tbActiveGoodsPo.setCreateTime(LocalDateTime.now());

            if (MulStateEnum.NO.getValue().equals(mulState)) {
                // 从商品重新获取核销方式和票付通参数（不确定前端是否会传参）
                TbGoodsPo goodsPo = goodsMapper.selectById(activeGood.getGoodsId());
                tbActiveGoodsPo.setVerifyType(goodsPo.getVerifyType());
                tbActiveGoodsPo.setPftSupplier(goodsPo.getPftSupplier());
                tbActiveGoodsPo.setPftProduct(goodsPo.getPftProduct());
                tbActiveGoodsPo.setPftTicket(goodsPo.getPftTicket());
            }

            int count = activeGoodsMapper.insert(tbActiveGoodsPo);
            if (count == 0) {
                log.error("添加活动失败，保存活动商品关联数据异常");
                Throw.isBusinessException("添加活动失败");
            }
        }
    }

    private void saveActiveGoodsSubsidyData(ActiveReleaseDto activeReleaseDto, Long activeId) {
        // 添加活动商品补贴数据
        if (SubsidyStateEnum.MANUAL.getValue().equals(activeReleaseDto.getSubsidyState()) && !CollectionUtils.isEmpty(activeReleaseDto.getActiveGoodsSubsidy())) {
            for (ActiveGoodsSubsidySonDto activeGoodsSubsidySonDto : activeReleaseDto.getActiveGoodsSubsidy()) {
                TbActiveGoodsSubsidyPo tbActiveGoodsSubsidyPo = new TbActiveGoodsSubsidyPo();
                BeanUtils.copyProperties(activeGoodsSubsidySonDto, tbActiveGoodsSubsidyPo);
                tbActiveGoodsSubsidyPo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveGoodsSubsidyPo.setActiveId(activeId);
                tbActiveGoodsSubsidyPo.setGoodsId(activeGoodsSubsidySonDto.getGoodsId());
                tbActiveGoodsSubsidyPo.setCreateTime(LocalDateTime.now());

                int count = activeGoodsSubsidyMapper.insert(tbActiveGoodsSubsidyPo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动商品补贴数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }
        }
    }

    // 添加活动折扣关联数据
    private void saveActiveDiscount(ActiveReleaseDto activeReleaseDto, Long activeId) {
        if (DiscountStateEnum.OPEN.getValue().equals(activeReleaseDto.getDiscountState()) && !CollectionUtils.isEmpty(activeReleaseDto.getActiveDiscount())) {
            for (ActiveDiscountSonDto activeDiscountSonDto : activeReleaseDto.getActiveDiscount()) {
                TbActiveDiscountPo tbActiveDiscountPo = new TbActiveDiscountPo();
                tbActiveDiscountPo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveDiscountPo.setActiveId(activeId);
                tbActiveDiscountPo.setNum(activeDiscountSonDto.getNum());
                tbActiveDiscountPo.setDiscount(activeDiscountSonDto.getDiscount());
                tbActiveDiscountPo.setCreateTime(LocalDateTime.now());

                int count = activeDiscountMapper.insert(tbActiveDiscountPo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动折扣关联数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }
        }
    }

}
